package com.yulongtian.algorithms.data_structure.level1;

import java.util.Arrays;

/**
 * https://leetcode.cn/problems/merge-sorted-array/
 *可
 * @author yulongTian
 * @create 2023-03-02 9:54
 */
public class Test03 {
    public static void main(String[] args) {
        int[] nums1 = new int[]{1, 2, 3, 0, 0, 0};
        int[] nums2 = new int[]{2, 5, 6};
        merge(nums1, nums1.length - nums2.length, nums2, nums2.length);
        System.out.println(Arrays.toString(nums1));
    }

    public static void merge(int[] nums1, int m, int[] nums2, int n) {
        int[] ans = new int[nums1.length];
        int p1 = 0, p2 = 0;
        int index = 0;
        while (p1 < m && p2 < n) {
            if (nums1[p1] < nums2[p2]) {
                ans[index++] = nums1[p1];
                p1++;
            } else if (nums1[p1] > nums2[p2]) {
                ans[index++] = nums2[p2];
                p2++;
            } else {
                ans[index++] = nums1[p1];
                ans[index++] = nums2[p2];
                p1++;
                p2++;
            }
        }
        if (p1 == m && p2 == n) {
            for (int i = 0; i < ans.length; i++) {
                nums1[i] = ans[i];
            }
            return;
        }

        if (p1 == m && p2 != n) {
            for (int i = p2; i < n; i++) {
                ans[index++] = nums2[i];
            }
            for (int i = 0; i < ans.length; i++) {
                nums1[i] = ans[i];
            }
            return;
        }

        if (p2 == n && p1 != m) {
            for (int i = p1; i < m; i++) {
                ans[index++] = nums1[i];
            }
            for (int i = 0; i < ans.length; i++) {
                nums1[i] = ans[i];
            }
            return;
        }
    }

}
